<template>
  <div class="authorization" v-loading="loading">
    <div class="authorization_top">
      <div class="authorization_top_appInfo tc">
        <span>
          {{ $t("sys.apply_name") }}：<span>{{ APP_INFO.appName }}</span>
        </span>
        <span class="ml70">
          {{ $t("sys.appUniqueId") }}：<span>{{ APP_INFO.appUniqueId }}</span>
        </span>
        <span class="ml70">
          {{ $t("sys.authorization_server_status") }}：
          <span class="item-content" :style="{ backgroundColor: LINE_STATUS_ENUM[line_status].color }"></span><span
            :style="{ color: LINE_STATUS_ENUM[line_status].color }">{{
                $t(LINE_STATUS_ENUM[line_status].i18n)
            }}</span>
        </span>
      </div>
      <div class="authorization_top_content">
        <el-form v-if="line_status === 'online'" :model="online_form" ref="online_form" label-width="150px">
          <el-form-item :label="$t('sys.activate_code') + ' ：'" prop="license" :rules="[
            {
              required: true,
              message: $t('sys.enter_authorization_code'),
              trigger: 'change',
            },
          ]">
            <el-input @blur="handleBlur" v-model="online_form.license"
              :placeholder="$t('sys.enter_authorization_code')" />
          </el-form-item>

          <template v-if="licenseType === 'TEST' || licenseType === 'FORMAL'">
            <el-form-item v-if="licenseType === 'FORMAL'" :label="$t('sys.dateType') + ' ：'" prop="dateType" :rules="[
              {
                required: true,
                message: $t('sys.select_dateType'),
                trigger: 'change',
              },
            ]">
              <el-radio-group v-model="online_form.dateType" @change="handleChange">
                <el-radio-button label="perpetual">{{
                    $t("sys.perpetual")
                }}</el-radio-button>
                <el-radio-button label="date">{{
                    $t("sys.date")
                }}</el-radio-button>
              </el-radio-group>
            </el-form-item>
            <el-form-item v-if="licenseType === 'TEST' || online_form.dateType === 'date'"
              :label="$t('sys.expiry_date') + ' ：'" prop="expiryDate" :rules="[
                {
                  required: true,
                  message: $t('sys.select_expiry_date'),
                  trigger: 'change',
                },
              ]">
              <el-date-picker :clearable="false" style="width: 100%" v-model="online_form.expiryDate" type="date"
                format="yyyy-MM-dd" value-format="yyyy-MM-dd" :placeholder="$t('sys.select_expiry_date')"
                :picker-options="{
                  disabledDate: disabledDateFun,
                }">
              </el-date-picker>
            </el-form-item>
          </template>
          <el-form-item :label="$t('sys.authorization_copyright_information') + ' ：'" prop="copyrightInfo" :rules="[
            {
              required: true,
              message: $t('sys.enter_copyright_information'),
              trigger: 'change',
            },
          ]">
            <el-input :maxlength="255" v-model="online_form.copyrightInfo"
              :placeholder="$t('sys.enter_copyright_information')" />
          </el-form-item>
          <el-form-item :label="$t('sys.authorization_archival_information') + ' ：'" prop="recordInfo">
            <el-input :maxlength="255" v-model="online_form.recordInfo"
              :placeholder="$t('sys.enter_archival_information')" />
          </el-form-item>
          <el-form-item class="tc mt60">
            <el-button class="dymBtn" type="primary" :loading="onlineActiveLoading" @click="onlineActivate">{{
                $t("sys.onlineActivate")
            }}</el-button>
          </el-form-item>
        </el-form>
        <el-form v-else :model="offline_form" ref="offline_form" label-width="120px">
          <el-form-item :label="$t('sys.activate_code') + ' ：'" prop="license" :rules="[
            {
              required: true,
              message: $t('sys.enter_authorization_code'),
              trigger: 'change',
            },
          ]">
            <el-input :placeholder="$t('sys.enter_authorization_code')" v-model="offline_form.license">
              <template slot="suffix">
                <el-popover placement="right" width="160" trigger="manual" :value="!!showPop">
                  <div class="tc">
                    <img :src="QRcodeUrl" width="126" height="126" />
                    <div>{{ $t("sys.miniappScanQRcode") }}</div>
                  </div>
                  <el-button slot="reference" style="margin-left: 20px" type="text" :loading="getFileLoading"
                    @click="getQRcode">{{ $t("sys.get_authorization_file") }}</el-button>
                </el-popover>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item :label="$t('sys.authorization_file') + ' ：'" prop="file" :rules="[
            {
              required: true,
              message: $t('sys.enter_authorization_file'),
              trigger: 'change',
            },
          ]">
            <Upload drag accept=".lic" v-model="offline_form.file" @input="clearValidate" :beforeUpload="beforeUpload">
            </Upload>
          </el-form-item>
          <el-form-item class="tc mt60">
            <el-button class="dymBtn" @click="offlineActivate" type="primary" :loading="offlineActiveLoading">{{
                $t("sys.activate")
            }}</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    <div>
      <div class="footer">
        <div class="footer_title">
          感谢您使用<span class="b">{{ APP_INFO.appName }}</span>系统：
        </div>
        <div class="footer_info b">1、试用版本可免费体验30天，无功能限制。</div>
        <div class="footer_info b">
          2、如果您已经购买激活码，请完成授权激活后继续使用系统。
        </div>
        <div class="footer_info b">3、如果您还未购买，可以联系我们购买。</div>
      </div>
    </div>
  </div>
</template>

<script>
import {
  getLicenseIsOnline,
  getRemoteActiveInfo,
  activeAuth,
  offlineActive,
  getLicenseType,
} from "@/customApi/license.js"
import { mapGetters } from "vuex"
import Upload from "./upload"
import QRCODE from "qrcode"
var moment = require("moment")
const LINE_STATUS_ENUM = {
  online: {
    i18n: "sys.online",
    color: "#4bbe4b",
  },
  offline: {
    i18n: "sys.offline",
    color: "#f34c4c",
  },
}
export default {
  name: "AuthComponents",
  components: { Upload },
  data() {
    return {
      LINE_STATUS_ENUM,
      loading: true,
      licenseType: "TRIAL",
      online_form: {
        license: "",
        dateType: "", //perpetual=>永久 date=>日期
        expiryDate: "",
        copyrightInfo: "",
        recordInfo: "",
      },
      offline_form: {
        license: "",
        file: "",
      },
      onlineActiveLoading: false,
      onlineActiveDisabled: false,
      getFileLoading: false,
      offlineActiveLoading: false,
      line_status: "offline",
      offlineTimer: null,
      fileList: [],
      QRcodeUrl: "",
      dialogVisible: false,
      showPop: false,
    }
  },
  computed: {
    ...mapGetters(["APP_INFO", "MOS_ENABLED"]),
  },
  created() {
    clearInterval(this.offlineTimer)
    this.judgeAthu()
    this.offlineTimer = setInterval(() => {
      this.judgeAthu()
    }, 20 * 1000)
  },
  destroyed() {
    clearInterval(this.offlineTimer)
  },
  methods: {
    // 获取在线状态
    judgeAthu() {
      getLicenseIsOnline()
        .then((res) => {
          this.line_status = res ? "online" : "offline"
          this.loading = false
        })
        .catch(() => {
          this.line_status = "offline"
          this.loading = false
        })
    },

    // 失焦 获取激活码类型
    async handleBlur() {
      if (!this.online_form.license) return
      this.onlineActiveDisabled = true
      try {
        let res = await getLicenseType({ license: this.online_form.license })
        this.licenseType = res
        if (!res || res === "TRIAL") {
          this.$set(this.online_form, "dateType", "")
          this.$set(this.online_form, "expiryDate", "")
          return
        } else if (res === "FORMAL") {
          this.$set(this.online_form, "dateType", "perpetual")
          this.$set(this.online_form, "expiryDate", "")
        } else {
          const year = new Date().getFullYear()
          this.$set(this.online_form, "dateType", "")
          this.$set(
            this.online_form,
            "expiryDate",
            moment(new Date(new Date().setFullYear(year + 1))).format(
              "YYYY-MM-DD"
            )
          )
        }
        this.onlineActiveDisabled = false
      } catch (error) {
        this.onlineActiveDisabled = false
      }
    },
    handleChange(v) {
      if (v === "perpetual") {
        this.$set(this.online_form, "expiryDate", "")
      } else {
        const year = new Date().getFullYear()
        this.$set(
          this.online_form,
          "expiryDate",
          moment(new Date(new Date().setFullYear(year + 1))).format(
            "YYYY-MM-DD"
          )
        )
      }
      this.$refs.online_form.validateField("expiryDate")
    },
    //禁选时间
    disabledDateFun(date) {
      if (this.licenseType === "FORMAL") {
        const allowDate = moment(new Date()).format("YYYY-MM-DD") + " 00:00:00"
        return date.getTime() < new Date(allowDate)
      } else if (this.licenseType === "TEST") {
        const year = new Date().getFullYear()
        const allowDateS = moment(new Date()).format("YYYY-MM-DD") + " 00:00:00"
        const allowDateE =
          moment(new Date(new Date().setFullYear(year + 1))).format(
            "YYYY-MM-DD"
          ) + " 23:59:59"

        return (
          date.getTime() < new Date(allowDateS) ||
          date.getTime() > new Date(allowDateE)
        )
      } else {
        return false
      }
    },
    // 获取离线激活二维码
    getQRcode() {
      this.showPop = false
      this.$refs.offline_form.validateField("license", async (errorMessage) => {
        if (errorMessage === "") {
          this.getFileLoading = true
          try {
            let res = await getRemoteActiveInfo({
              license: this.offline_form.license,
            })
            if (res) {
              this.QRcodeUrl = await QRCODE.toDataURL(res, {
                margin: 2,
              })
              this.getFileLoading = false
              this.dialogVisible = true
              this.showPop = true
            } else {
              this.getFileLoading = false
            }
          } catch (e) {
            this.getFileLoading = false
          }
        }
      })
    },
    // 在线激活
    onlineActivate() {
      if (this.onlineActiveDisabled) return
      this.$refs.online_form.validate((valid) => {
        if (valid) {
          this.onlineActiveLoading = true
          let { license, expiryDate, copyrightInfo, recordInfo } =
            this.online_form
          const data = {
            license,
            expiryDate,
            copyrightInfo,
            recordInfo,
          }
          activeAuth(data)
            .then(async (res) => {
              this.$message.success(this.$t("激活成功"))
              await this.$store.dispatch("GetLicenseInfoDto")
              this.$emit('changeStatus', { type: 'active' })
            })
            .finally(() => {
              this.onlineActiveLoading = false
            })
        }
      })
    },
    //离线激活
    offlineActivate() {
      this.$refs.offline_form.validate((valid) => {
        if (valid) {
          this.offlineActiveLoading = true
          console.log(this.offline_form)
          const formData = new FormData()
          formData.append("files", this.offline_form.file)
          offlineActive(formData, {
            license: this.offline_form.license,
          })
            .then(async (res) => {
              this.$message.success(this.$t("激活成功"))
              await this.$store.dispatch("GetLicenseInfoDto")
              this.$emit('changeStatus', { type: 'active' })
            })
            .finally(() => {
              this.offlineActiveLoading = false
            })
        } else {
        }
      })
    },
    clearValidate() {
      this.$refs.offline_form.clearValidate("file")
    },
    beforeUpload(file) {
      const type = file.name.split(".").pop().toLowerCase()
      if (["lic"].includes(type)) {
        return true
      } else {
        this.$message.error("只能上传lic格式的授权文件")
        return false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.authorization {
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  height: 100%;
  min-width: 1000px;

  &_top {
    flex: 1 1 0%;
    display: flex;
    flex-direction: column;

    &_header {
      height: 56px;
      line-height: 56px;
      margin-bottom: 24px;

      .container {
        text-align: center;

        .title {
          font-size: 24px;
          font-weight: 600;
        }
      }
    }

    &_appInfo {
      margin: 24px 83px;
      background-color: rgba(237, 237, 237, 1);
      border-radius: 4px;
      line-height: 44px;
      border: 1px rgba(231, 231, 231, 1);

      .ml70 {
        margin-left: 70px;
      }

      .item-content {
        display: inline-block;
        width: 6px;
        height: 6px;
        border-radius: 50%;
        background-color: #f34c4c;
        margin-right: 5px;
        vertical-align: inherit;
        position: relative;
        top: -2px;
      }
    }

    &_content {
      flex: 1;
      display: flex;
      justify-content: center;
      align-items: center;

      .el-form {
        width: 600px;
      }

      ::v-deep .el-upload {
        width: 100%;
      }

      ::v-deep .el-upload-dragger {
        width: 100%;
      }

      .dymBtn {
        width: 176px;
      }
    }
  }

  .footer {
    padding: 33px 130px 40px;
    background: #ebf3fe;
    border-radius: 4px;

    &_title {
      color: #69717c;
      margin-bottom: 22px;
      font-size: 14px;
    }

    &_info {
      font-size: 12px;
      color: #2b3648;
      line-height: 30px;
    }
  }
}
</style>
